# coding: utf-8
import re
import urllib

from tornado.web import RequestHandler, HTTPError
from tornado import template, ioloop, escape
from jinja2 import Environment,FileSystemLoader
from config import settings
from app import myapp
from app.helper.util import storify

class AbstractHandler(RequestHandler):
    def __init__(self, application, request, **kwargs):
        super(AbstractHandler, self).__init__(application, request, **kwargs)

    def get_current_user(self):
        test_user={"username":"admin","role":1}
        return test_user

    @property
    def is_admin(self):
        return self.current_user['role'] >= 1 if self.current_user['role'] else False

    #要实现url正反解析
    def url(self,udi,para):
        pass

    def input(self,*requireds, **defaults):
        out = self.request.arguments
        try:
            defaults.setdefault('_unicode', True) # force unicode conversion by default.
            return storify(out, *requireds, **defaults)
        except KeyError:
            raise HTTPError(403)

    def prepare(self):
        self._context = myapp._Context()
        self._remove_slash()
        if not self.is_admin:
           if self.request.method == "GET":
              url="/admin/login"
              if "?" not in url:
                 url += "?" + urllib.urlencode(dict(next=self.request.full_url()))
                 return self.redirect(url)
        super(AbstractHandler, self).prepare()

    def render(self,**kwargs):
        html = self.render_string(**kwargs)
        return self.finish(html)
        
    
    def render_string(self,**kwargs):
        extensions = kwargs.pop('extensions', [])
        globals = kwargs.pop('globals', {})

        globals['config']=settings.admin_config
        globals['current_user']=self.current_user

        globals['context'] = self._context
        
        jinja_env = Environment(
           #os.path.join(os.path.dirname(__file__), 'templates')
           loader=FileSystemLoader('templates/admin',encoding='utf-8'),
           extensions=extensions, )
        jinja_env.globals.update(globals)
        #jinja_env.update_template_context(context)
        
        template=""
        if "template_name" in kwargs:
           template=kwargs['template_name'].replace('_','/')+".html"
        else:
           class_name=self.__class__.__name__
           template=class_name.replace('_','/')+".html"
        return jinja_env.get_template(template).render(**kwargs)
        return super(AbstractHandler, self).render_string(**kwargs)

    def flush(self, include_footers=False):
        """Flushes the current output buffer to the network."""
        if self.application._wsgi:
            raise Exception("WSGI applications do not support flush()")

        chunk = "".join(self._write_buffer)
        # keep write buffer for cache
        # self._write_buffer = []
        if not self._headers_written:
            self._headers_written = True
            for transform in self._transforms:
                self._headers, chunk = transform.transform_first_chunk(
                    self._headers, chunk, include_footers)
            headers = self._generate_headers()
        else:
            for transform in self._transforms:
                chunk = transform.transform_chunk(chunk, include_footers)
            headers = ""

        # Ignore the chunk and only write the headers for HEAD requests
        if self.request.method == "HEAD":
            if headers: self.request.write(headers)
            return

        if headers or chunk:
            self.request.write(headers + chunk)

    def _remove_slash(self):
        if self.request.method == "GET":
            _remove_slash_re = re.compile(".+/$")
            if _remove_slash_re.match(self.request.path):
                # remove trail slash in path
                uri = self.request.path.rstrip("/")
                if self.request.query:
                    uri += "?" + self.request.query

                self.redirect(uri)




base=AbstractHandler
